package com.zyx.maildemo.controller;

import com.zyx.maildemo.config.jwt.JWTUtils;
import com.zyx.maildemo.entity.User;
import com.zyx.maildemo.service.UserService;
import com.zyx.maildemo.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: UserController
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/7/27 16:02
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    private String host;

    private final JWTUtils jwtUtils;
    private final UserService userService;

    @Autowired
    public UserController(JWTUtils jwtUtils, UserService userService) {
        this.jwtUtils = jwtUtils;
        this.userService = userService;
    }

    @ModelAttribute
    public void setToken(HttpServletRequest request,
                         @RequestHeader(value = "token", required = false, defaultValue = "") String headerToken,
                         @RequestParam(value = "token", required = false) String pToken) {
        StringBuffer requestURL = request.getRequestURL();
        int i = requestURL.indexOf("/", 8);
        if (i != -1) {
            host = requestURL.substring(0, i);
        } else {
            host = String.valueOf(requestURL);
        }
        String token = headerToken;
        if (StringUtils.isEmpty(token)) {
            token = pToken;
        }
        request.setAttribute("token", token);
    }

    @PostMapping("/register")
    public RestResponse register(User user) {
        if (userService.findByName(user.getUsername()) != null)
            return RestResponse.fail("用户名已经使用!");
        boolean register = userService.register(user);
        if (register)
            return RestResponse.ok(user);
        return RestResponse.fail("注册失败");
    }

    @PostMapping("/login")
    public RestResponse login(User user) {
        try {
            if (userService.login(user)) {
                String sign = jwtUtils.sign(user.getUsername(), user.getPassword());
                return RestResponse.ok(sign);
            }
        } catch (AuthenticationException e) {
            return RestResponse.fail("登录失败: " + e.getMessage());
        }
        return RestResponse.fail("登录失败!");
    }

    @PostMapping("/delete")
    @RequiresRoles({"admin"})
    public RestResponse delete(@RequestAttribute("token") String token) {
        String username = jwtUtils.getUsername(token);
        User byName = userService.findByName(username);
        return RestResponse.ok("删除成功");
    }

}
